package cn.xing.modules.sys.service.impl;

import cn.xing.enums.ChartTimeUnitEnum;
import cn.xing.modules.app.entity.OrderEntity;
import cn.xing.modules.app.entity.OrderItemEntity;
import cn.xing.modules.app.entity.ProductCategoryEntity;
import cn.xing.modules.app.service.OrderItemService;
import cn.xing.modules.app.service.OrderService;
import cn.xing.modules.app.service.ProductCategoryService;
import cn.xing.modules.sys.service.ChartService;
import cn.xing.modules.sys.vo.OrderCountLineVo;
import cn.xing.modules.sys.vo.OrderCountVo;
import cn.xing.modules.sys.vo.SaleCountPieVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ChartServiceImpl implements ChartService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Override
    public OrderCountLineVo queryLineUnion(ChartTimeUnitEnum timeUnitEnum, String startTime, String endTime) {
        OrderCountLineVo orderCountLineVo = new OrderCountLineVo();

        List<OrderCountVo> orderCountVos = orderService.queryOrderCountByTimeUnit(timeUnitEnum,startTime,endTime);
        orderCountLineVo.setOrderCountVoList(orderCountVos);

        return  orderCountLineVo;
    }

    @Override
    public List<SaleCountPieVo> querySaleCountPieDataList(String startTime, String endTime) {
        Map<Long, Integer> categorySaleCountMap = new HashMap<Long, Integer>();
        // 1. 查询 付款 及以后 的订单
        List<OrderEntity> orderEntityList = orderService.queryPayed( startTime,endTime);

        // 2.查询orderItem
        for (OrderEntity orderEntity : orderEntityList) {
            String orderSn = orderEntity.getOrderSn();
            List<OrderItemEntity> orderItemEntities = orderItemService.queryByOrderSn(orderSn);

            // 3. 累加
            for (OrderItemEntity orderItemEntity : orderItemEntities) {
                Long categoryId = orderItemEntity.getCategoryId();
                Integer num = orderItemEntity.getNum();

                Integer sum = categorySaleCountMap.getOrDefault(categoryId, 0);
                categorySaleCountMap.put(categoryId, sum + num);
            }
        }

        List<SaleCountPieVo> saleCountPieVos = new ArrayList<>();

        Set<Map.Entry<Long, Integer>> entrySet = categorySaleCountMap.entrySet();
        for (Map.Entry<Long, Integer> categorySaleCountEntry : entrySet) {
            // 查询 分类名称
            ProductCategoryEntity categoryEntity = productCategoryService.getById(categorySaleCountEntry.getKey());

            // 集合
            saleCountPieVos.add(new SaleCountPieVo(categoryEntity.getName(), categorySaleCountEntry.getValue()));
        }

        return saleCountPieVos;
    }
}
